﻿using System;
using System.Threading;

namespace Bouyei.NetworkSniffer
{
    using Collections;

    public class RawPacketQueue
    {
        LinkQueue<RawPacket> collection = null;
        int used = 0;

        public int Count
        {
            get { return collection.Count; }
        }

        public RawPacketQueue()
        {
            collection = new LinkQueue<RawPacket>();
        }

        public void AddQueue(RawPacket rawPacket)
        {
            while (Interlocked.CompareExchange(ref used, 1, 0) != 0)
            {
                Thread.Sleep(1);
            }
            try
            {
                collection.Enqueue(rawPacket);
            }
            finally
            {
                used = 0;
            }
        }

        public RawPacket RemoveQueue()
        {
            while (Interlocked.CompareExchange(ref used, 1, 0) != 0)
            {
                Thread.Sleep(1);
            }
            try
            {
                return collection.Dequeue();
            }
            finally
            {
                used = 0;
            }
        }

        public void Clear()
        {
            while (Interlocked.CompareExchange(ref used, 1, 0) != 0)
            {
                Thread.Sleep(1);
            }
            try
            {
                collection.Clear();
            }
            finally
            {
                used = 0;
            }
        }
    }
}
